package com.situ.blog.dao.impl;

import com.situ.blog.dao.IBlogDao;
import com.situ.blog.pojo.entity.Blog;
import com.situ.blog.pojo.query.BlogQuery;
import com.situ.blog.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

public class BlogDaoImpl implements IBlogDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    //如果name和typeId全是null，则全部打印：select * from blog where 1=1
    //如果一方不为null,则sql拼接
    @Override
    public List<Blog> selectSearch(BlogQuery blogQuery) {
        String sql = "select * from blog where 1=1";
        /*String sql = "SELECT b.id,b.`name`,b.type_id,t.id AS typeId,t.`name` AS typeName\n" +
                "FROM blog AS b INNER JOIN blog_type AS t \n" +
                "ON b.type_id=t.id where 1=1";*/

        List<Object> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(blogQuery.getTypeId())){
            sql += " and type_id=?";
            list.add(blogQuery.getTypeId());
        }
        if (!ObjectUtils.isEmpty(blogQuery.getName())){
            sql += " and name like ?";
            list.add("%" + blogQuery.getName() + "%");
        }
        return template.query(sql,new BeanPropertyRowMapper<>(Blog.class),list.toArray());
    }

    @Override
    public Blog selectById(int id) {
        return template.queryForObject("select * from blog where id=?",
                new BeanPropertyRowMapper<>(Blog.class),id);
    }

    //不用Query封装
   /* @Override
    public List<Blog> selectSearch(Integer typeId, String name) {
        String sql = "select * from blog where 1=1";
        List<Object> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(typeId)){
            sql += " and type_id=?";
            list.add(typeId);
        }
        if (!ObjectUtils.isEmpty(name)){
            sql += " and name like ?";
            list.add("%" + name + "%");
        }
        return template.query(sql,new BeanPropertyRowMapper<>(Blog.class),list.toArray());
    }*/


    //单元素搜索
    /*@Override
    public List<Blog> selectByType(Integer typeId) {
        String sql = "select * from blog where 1=1";
        List<Object> list = new ArrayList<>();
        if (!ObjectUtils.isEmpty(typeId)){
            sql += " and type_id=?";
            list.add(typeId);
        }

        return template.query(sql,new BeanPropertyRowMapper<>(Blog.class),list.toArray());
    }*/
}
